package com.kool.kmetrics.consumer;

import com.alibaba.fastjson.JSON;
import com.kool.kmetrics.consumer.vo.KafkaMsg;
import com.kool.kmetrics.service.MetricsService;
import com.kool.kmetrics.common.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author luyu
 */
@Component
@Slf4j
public class KafkaConsumer {
    @Resource
    private MetricsService metricsService;

    /**
     * 消费kafka消息
     *
     * @param kafkaMessage
     */
    @KafkaListener(id = "${kafka.group.kmetrics_group}", topics = {"#{'${log_topics}'.split(',')}"})
    public void consume(String kafkaMessage) {
        KafkaMsg kafkaMsg = JSON.parseObject(kafkaMessage, KafkaMsg.class);
        String topicSuffix = kafkaMsg.getTopicSuffix();
        if (StringUtil.isEmpty(topicSuffix)) {
            return;
        }

        if (!TopicConstant.TOPIC_SUFFIX_SEND_LOG.equals(topicSuffix)
                && !TopicConstant.TOPIC_SUFFIX_RECEIVE_LOG.equals(topicSuffix)
                && !TopicConstant.TOPIC_SUFFIX_SESSION_LOG.equals(topicSuffix)
                && !TopicConstant.TOPIC_SUFFIX_SUBSCRIPTION_LOG.equals(topicSuffix)
                && !TopicConstant.TOPIC_SUFFIX_NO_ACK_SEND_PACKET_LOG.equals(topicSuffix)) {
            return;
        }
        String message = kafkaMsg.getMessage();
        metricsService.dispatch(topicSuffix, message);
    }

}
